Passed
Pull Request — master (#995)
by
unknown
06:59
created

script.js ➔ trash   A

Complexity

Conditions 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
dl 0
loc 7
rs 10
1
var lfm_route = location.origin + location.pathname;
2
var show_list;
3
var sort_type = 'alphabetic';
4
var multi_selection_enabled = false;
5
var selected = [];
6
var items = [];
7
8
$.fn.fab = function (options) {
9
  var menu = this;
10
  menu.addClass('fab-wrapper');
11
12
  var toggler = $('<a>')
13
    .addClass('fab-button fab-toggle')
14
    .append($('<i>').addClass('fas fa-plus'))
15
    .click(function () {
16
      menu.toggleClass('fab-expand');
17
    });
18
19
  menu.append(toggler);
20
21
  options.buttons.forEach(function (button) {
22
    toggler.before(
23
      $('<a>').addClass('fab-button fab-action')
24
        .attr('data-label', button.label)
25
        .attr('id', button.attrs.id)
26
        .append($('<i>').addClass(button.icon))
27
        .click(function () {
28
          menu.removeClass('fab-expand');
29
        })
30
    );
31
  });
32
};
33
34
$(document).ready(function () {
35
  $('#fab').fab({
36
    buttons: [
37
      {
38
        icon: 'fas fa-upload',
39
        label: lang['nav-upload'],
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
40
        attrs: {id: 'upload'}
41
      },
42
      {
43
        icon: 'fas fa-folder',
44
        label: lang['nav-new'],
45
        attrs: {id: 'add-folder'}
46
      }
47
    ]
48
  });
49
50
  actions.reverse().forEach(function (action) {
0 ignored issues
show
Bug introduced by
The variable actions seems to be never declared. If this is a global, consider adding a /** global: actions */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
51
    $('#nav-buttons > ul').prepend(
52
      $('<li>').addClass('nav-item').append(
53
        $('<a>').addClass('nav-link d-none')
54
          .attr('data-action', action.name)
55
          .attr('data-multiple', action.multiple)
56
          .append($('<i>').addClass('fas fa-fw fa-' + action.icon))
57
          .append($('<span>').text(action.label))
58
      )
59
    );
60
  });
61
62
  sortings.forEach(function (sort) {
0 ignored issues
show
Bug introduced by
The variable sortings seems to be never declared. If this is a global, consider adding a /** global: sortings */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
63
    $('#nav-buttons .dropdown-menu').append(
64
      $('<a>').addClass('dropdown-item').attr('data-sortby', sort.by)
65
        .append($('<i>').addClass('fas fa-fw fa-' + sort.icon))
66
        .append($('<span>').text(sort.label))
67
        .click(function() {
68
          sort_type = sort.by;
69
          loadItems();
70
        })
71
    );
72
  });
73
74
  loadFolders();
75
  performLfmRequest('errors')
76
    .done(function (response) {
77
      JSON.parse(response).forEach(function (message) {
78
        $('#alerts').append(
79
          $('<div>').addClass('alert alert-warning')
80
            .append($('<i>').addClass('fas fa-exclamation-circle'))
81
            .append(' ' + message)
82
        );
83
      });
84
    });
85
86
  $(window).on('dragenter', function(){
87
    $('#uploadModal').modal('show');
88
  });
89
90
  if (usingWysiwygEditor()) {
91
    $('#multi_selection_toggle').hide();
92
  }
93
});
94
95
// ======================
96
// ==  Navbar actions  ==
97
// ======================
98
99
$('#multi_selection_toggle').click(function () {
100
  multi_selection_enabled = !multi_selection_enabled;
101
102
  $('#multi_selection_toggle i')
103
    .toggleClass('fa-times', multi_selection_enabled)
104
    .toggleClass('fa-check-double', !multi_selection_enabled);
105
106
  if (!multi_selection_enabled) {
107
    clearSelected();
108
  }
109
});
110
111
$('#to-previous').click(function () {
112
  var previous_dir = getPreviousDir();
113
  if (previous_dir == '') return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
114
  goTo(previous_dir);
115
});
116
117
function toggleMobileTree(should_display) {
118
  if (should_display === undefined) {
119
    should_display = !$('#tree').hasClass('in');
120
  }
121
  $('#tree').toggleClass('in', should_display);
122
}
123
124
$('#show_tree').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
125
  toggleMobileTree();
126
});
127
128
$('#main').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
129
  if ($('#tree').hasClass('in')) {
130
    toggleMobileTree(false);
131
  }
132
});
133
134
$(document).on('click', '#add-folder', function () {
135
  dialog(lang['message-name'], '', createFolder);
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
136
});
137
138
$(document).on('click', '#upload', function () {
139
  $('#uploadModal').modal('show');
140
});
141
142
$(document).on('click', '[data-display]', function() {
143
  show_list = $(this).data('display');
144
  loadItems();
145
});
146
147
$(document).on('click', '#keyword-button', function() {
148
  show_list = $(this).data('display');
149
  loadItems();
150
});
151
152
$(document).on('click', '#keyword-reset-button', function() {
153
  $('#keyword').val("");
154
  show_list = $(this).data('display');
155
  loadItems();
156
});
157
158
$(document).on('click', '[data-action]', function() {
159
  window[$(this).data('action')]($(this).data('multiple') ? getSelectedItems() : getOneSelectedElement());
160
});
161
162
// ==========================
163
// ==  Multiple Selection  ==
164
// ==========================
165
166
function toggleSelected (e) {
167
  if (!multi_selection_enabled) {
168
    selected = [];
169
  }
170
171
  var sequence = $(e.target).closest('a').data('id');
172
  var element_index = selected.indexOf(sequence);
173
  if (element_index === -1) {
174
    selected.push(sequence);
175
  } else {
176
    selected.splice(element_index, 1);
177
  }
178
179
  updateSelectedStyle();
180
}
181
182
function clearSelected () {
183
  selected = [];
184
185
  multi_selection_enabled = false;
186
187
  updateSelectedStyle();
188
}
189
190
function updateSelectedStyle() {
191
  items.forEach(function (item, index) {
192
    $('[data-id=' + index + ']')
193
      .find('.square')
194
      .toggleClass('selected', selected.indexOf(index) > -1);
195
  });
196
  toggleActions();
197
}
198
199
function getOneSelectedElement(orderOfItem) {
200
  var index = orderOfItem !== undefined ? orderOfItem : selected[0];
201
  return items[index];
202
}
203
204
function getSelectedItems() {
205
  return selected.reduce(function (arr_objects, id) {
206
    arr_objects.push(getOneSelectedElement(id));
207
    return arr_objects
208
  }, []);
209
}
210
211
function toggleActions() {
212
  var one_selected = selected.length === 1;
213
  var many_selected = selected.length >= 1;
214
  var only_image = getSelectedItems()
215
    .filter(function (item) { return !item.is_image; })
216
    .length === 0;
217
  var only_file = getSelectedItems()
218
    .filter(function (item) { return !item.is_file; })
219
    .length === 0;
220
221
  $('[data-action=use]').toggleClass('d-none', !(many_selected && only_file));
222
  $('[data-action=rename]').toggleClass('d-none', !one_selected);
223
  $('[data-action=preview]').toggleClass('d-none', !(many_selected && only_file));
224
  $('[data-action=move]').toggleClass('d-none', !many_selected);
225
  $('[data-action=download]').toggleClass('d-none', !(many_selected && only_file));
226
  $('[data-action=resize]').toggleClass('d-none', !(one_selected && only_image));
227
  $('[data-action=crop]').toggleClass('d-none', !(one_selected && only_image));
228
  $('[data-action=trash]').toggleClass('d-none', !many_selected);
229
  $('[data-action=open]').toggleClass('d-none', !one_selected || only_file);
230
  $('#multi_selection_toggle').toggleClass('d-none', usingWysiwygEditor() || !many_selected);
231
  $('#actions').toggleClass('d-none', selected.length === 0);
232
  $('#fab').toggleClass('d-none', selected.length !== 0);
233
}
234
235
// ======================
236
// ==  Folder actions  ==
237
// ======================
238
239
$(document).on('click', '#tree a', function (e) {
240
  goTo($(e.target).closest('a').data('path'));
241
  toggleMobileTree(false);
242
});
243
244
function goTo(new_dir) {
245
  $('#working_dir').val(new_dir);
246
  loadItems();
247
}
248
249
function getPreviousDir() {
250
  var working_dir = $('#working_dir').val();
251
  return working_dir.substring(0, working_dir.lastIndexOf('/'));
252
}
253
254
function setOpenFolders() {
255
  $('#tree [data-path]').each(function (index, folder) {
256
    // close folders that are not parent
257
    var should_open = ($('#working_dir').val() + '/').startsWith($(folder).data('path') + '/');
258
    $(folder).children('i')
259
      .toggleClass('fa-folder-open', should_open)
260
      .toggleClass('fa-folder', !should_open);
261
  });
262
263
  $('#tree .nav-item').removeClass('active');
264
  $('#tree [data-path="' + $('#working_dir').val() + '"]').parent('.nav-item').addClass('active');
265
}
266
267
// ====================
268
// ==  Ajax actions  ==
269
// ====================
270
271
function performLfmRequest(url, parameter, type) {
272
  var data = defaultParameters();
273
274
  if (parameter != null) {
0 ignored issues
show
Best Practice introduced by
Comparing parameter to null using the != operator is not safe. Consider using !== instead.
Loading history...
275
    $.each(parameter, function (key, value) {
276
      data[key] = value;
277
    });
278
  }
279
280
  return $.ajax({
281
    type: 'GET',
282
    beforeSend: function(request) {
283
      var token = getUrlParam('token');
284
      if (token !== null) {
285
        request.setRequestHeader("Authorization", 'Bearer ' + token);
286
      }
287
    },
288
    dataType: type || 'text',
289
    url: lfm_route + '/' + url,
290
    data: data,
291
    cache: false
292
  }).fail(function (jqXHR, textStatus, errorThrown) {
0 ignored issues
show
Unused Code introduced by
The parameter errorThrown is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter textStatus is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
293
    displayErrorResponse(jqXHR);
294
  });
295
}
296
297
function displayErrorResponse(jqXHR) {
298
  notify('<div style="max-height:50vh;overflow: scroll;">' + jqXHR.responseText + '</div>');
299
}
300
301
var refreshFoldersAndItems = function (data) {
302
  loadFolders();
303
  if (data != 'OK') {
304
    data = Array.isArray(data) ? data.join('<br/>') : data;
305
    notify(data);
306
  }
307
};
308
309
var hideNavAndShowEditor = function (data) {
310
  $('#nav-buttons > ul').addClass('d-none');
311
  $('#content').html(data);
312
  $('#pagination').removeClass('preserve_actions_space')
313
  clearSelected();
314
}
315
316
function loadFolders() {
317
  performLfmRequest('folders', {}, 'html')
318
    .done(function (data) {
319
      $('#tree').html(data);
320
      loadItems();
321
    });
322
}
323
324
function generatePaginationHTML(el, args) {
325
  var template = '<li class="page-item"><\/li>';
326
  var linkTemplate = '<a class="page-link"><\/a>';
327
  var currentPage = args.currentPage;
328
  var totalPage = args.totalPage;
329
  var rangeStart = args.rangeStart;
330
  var rangeEnd = args.rangeEnd;
331
  var i;
332
333
  // Disable page range, display all the pages
334
  if (args.pageRange === null) {
335
    for (i = 1; i <= totalPage; i++) {
336
      var button = $(template)
337
        .attr('data-num', i)
338
        .append($(linkTemplate).html(i));
339
      if (i == currentPage) {
340
        button.addClass('active');
341
      }
342
      el.append(button);
343
    }
344
345
    return;
346
  }
347
348
  if (rangeStart <= 3) {
349
    for (i = 1; i < rangeStart; i++) {
350
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
351
        .attr('data-num', i)
352
        .append($(linkTemplate).html(i));
353
      if (i == currentPage) {
354
        button.addClass('active');
355
      }
356
      el.append(button);
357
    }
358
  } else {
359
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
360
      .attr('data-num', 1)
361
      .append($(linkTemplate).html(1));
362
    el.append(button);
363
364
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
365
      .addClass('disabled')
366
      .append($(linkTemplate).html('...'));
367
    el.append(button);
368
  }
369
370
  for (i = rangeStart; i <= rangeEnd; i++) {
371
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
372
      .attr('data-num', i)
373
      .append($(linkTemplate).html(i));
374
    if (i == currentPage) {
375
      button.addClass('active');
376
    }
377
    el.append(button);
378
  }
379
380
  if (rangeEnd >= totalPage - 2) {
381
    for (i = rangeEnd + 1; i <= totalPage; i++) {
382
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
383
        .attr('data-num', i)
384
        .append($(linkTemplate).html(i));
385
      el.append(button);
386
    }
387
  } else {
388
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
389
      .addClass('disabled')
390
      .append($(linkTemplate).html('...'));
391
    el.append(button);
392
393
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 336. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
394
      .attr('data-num', totalPage)
395
      .append($(linkTemplate).html(totalPage));
396
    el.append(button);
397
  }
398
}
399
400
function createPagination(paginationSetting) {
401
  var el = $('<ul class="pagination" role="navigation"></ul>');
402
403
  var currentPage = paginationSetting.current_page;
404
  var pageRange = 5;
405
  var totalPage = Math.ceil(paginationSetting.total / paginationSetting.per_page);
406
407
  var rangeStart = currentPage - pageRange;
408
  var rangeEnd = currentPage + pageRange;
409
410
  if (rangeEnd > totalPage) {
411
    rangeEnd = totalPage;
412
    rangeStart = totalPage - pageRange * 2;
413
    rangeStart = rangeStart < 1 ? 1 : rangeStart;
414
  }
415
416
  if (rangeStart <= 1) {
417
    rangeStart = 1;
418
    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
419
  }
420
421
  generatePaginationHTML(el, {
422
    totalPage: totalPage,
423
    currentPage: currentPage,
424
    pageRange: pageRange,
425
    rangeStart: rangeStart,
426
    rangeEnd: rangeEnd
427
  });
428
429
  $('#pagination').append(el);
430
}
431
432
function loadItems(page) {
433
  loading(true);
434
  var keyword = $('#keyword').val();
0 ignored issues
show
Unused Code introduced by
The variable keyword seems to be never used. Consider removing it.
Loading history...
435
  performLfmRequest('jsonitems', {show_list: show_list, sort_type: sort_type, page: page || 1}, 'html')
436
    .done(function (data) {
437
      selected = [];
438
      var response = JSON.parse(data);
439
      var working_dir = response.working_dir;
440
      items = response.items;
441
      var hasItems = items.length !== 0;
442
      var hasPaginator = !!response.paginator;
443
      $('#empty').toggleClass('d-none', hasItems);
444
      $('#content').html('').removeAttr('class');
445
      $('#pagination').html('').removeAttr('class');
446
447
      if (hasItems) {
448
        $('#content').addClass(response.display);
449
        $('#pagination').addClass('preserve_actions_space');
450
451
        items.forEach(function (item, index) {
452
          var template = $('#item-template').clone()
453
            .removeAttr('id class')
454
            .attr('data-id', index)
455
            .click(toggleSelected)
456
            .dblclick(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
457
              if (item.is_file) {
458
                use(getSelectedItems());
459
              } else {
460
                goTo(item.url);
461
              }
462
            });
463
464
          if (item.thumb_url) {
465
            var image = $('<div>').css('background-image', 'url("' + item.thumb_url + '?timestamp=' + item.time + '")');
466
          } else {
467
            var icon = $('<div>').addClass('ico');
468
            var image = $('<div>').addClass('mime-icon ico-' + item.icon).append(icon);
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable image already seems to be declared on line 465. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
469
          }
470
471
          template.find('.square').append(image);
472
          template.find('.item_name').text(item.name);
473
          template.find('time').text((new Date(item.time * 1000)).toLocaleString());
474
475
          $('#content').append(template);
476
        });
477
      }
478
479
      if (hasPaginator) {
480
        createPagination(response.paginator);
481
482
        $('#pagination a').on('click', function(event) {
483
          event.preventDefault();
484
485
          loadItems($(this).closest('li')[0].getAttribute('data-num'));
486
487
          return false;
488
        });
489
      }
490
491
      $('#nav-buttons > ul').removeClass('d-none');
492
493
      $('#working_dir').val(working_dir);
494
      console.log('Current working_dir : ' + working_dir);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
495
      var breadcrumbs = [];
496
      var validSegments = working_dir.split('/').filter(function (e) { return e; });
497
      validSegments.forEach(function (segment, index) {
498
        if (index === 0) {
499
          // set root folder name as the first breadcrumb
500
          breadcrumbs.push($("[data-path='/" + segment + "']").text());
501
        } else {
502
          breadcrumbs.push(segment);
503
        }
504
      });
505
506
      $('#current_folder').text(breadcrumbs[breadcrumbs.length - 1]);
507
      $('#breadcrumbs > ol').html('');
508
      breadcrumbs.forEach(function (breadcrumb, index) {
509
        var li = $('<li>').addClass('breadcrumb-item').text(breadcrumb);
510
511
        if (index === breadcrumbs.length - 1) {
512
          li.addClass('active').attr('aria-current', 'page');
513
        } else {
514
          li.click(function () {
515
            // go to corresponding path
516
            goTo('/' + validSegments.slice(0, 1 + index).join('/'));
517
          });
518
        }
519
520
        $('#breadcrumbs > ol').append(li);
521
      });
522
523
      var atRootFolder = getPreviousDir() == '';
524
      $('#to-previous').toggleClass('d-none invisible-lg', atRootFolder);
525
      $('#show_tree').toggleClass('d-none', !atRootFolder).toggleClass('d-block', atRootFolder);
526
      setOpenFolders();
527
      loading(false);
528
      toggleActions();
529
    });
530
}
531
532
function loading(show_loading) {
533
  $('#loading').toggleClass('d-none', !show_loading);
534
}
535
536
function createFolder(folder_name) {
537
  performLfmRequest('newfolder', {name: folder_name})
538
    .done(refreshFoldersAndItems);
539
}
540
541
// ==================================
542
// ==         File Actions         ==
543
// ==================================
544
545
function rename(item) {
546
  dialog(lang['message-rename'], item.name, function (new_name) {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
547
    performLfmRequest('rename', {
548
      file: item.name,
549
      new_name: new_name
550
    }).done(refreshFoldersAndItems);
551
  });
552
}
553
554
function trash(items) {
555
  notify(lang['message-delete'], function () {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
556
    performLfmRequest('delete', {
557
      items: items.map(function (item) { return item.name; })
558
    }).done(refreshFoldersAndItems)
559
  });
560
}
561
562
function crop(item) {
563
  performLfmRequest('crop', {img: item.name})
564
    .done(hideNavAndShowEditor);
565
}
566
567
function resize(item) {
568
  performLfmRequest('resize', {img: item.name})
569
    .done(hideNavAndShowEditor);
570
}
571
572
function download(items) {
573
  items.forEach(function (item, index) {
574
    var data = defaultParameters();
575
576
    data['file'] = item.name;
577
578
    var token = getUrlParam('token');
579
    if (token) {
580
      data['token'] = token;
581
    }
582
583
    setTimeout(function () {
584
      location.href = lfm_route + '/download?' + $.param(data);
585
    }, index * 100);
586
  });
587
}
588
589
function open(item) {
590
  goTo(item.url);
591
}
592
593
function preview(items) {
594
  var carousel = $('#carouselTemplate').clone().attr('id', 'previewCarousel').removeClass('d-none');
595
  var imageTemplate = carousel.find('.carousel-item').clone().removeClass('active');
596
  var indicatorTemplate = carousel.find('.carousel-indicators > li').clone().removeClass('active');
597
  carousel.children('.carousel-inner').html('');
598
  carousel.children('.carousel-indicators').html('');
599
  carousel.children('.carousel-indicators,.carousel-control-prev,.carousel-control-next').toggle(items.length > 1);
600
601
  items.forEach(function (item, index) {
602
    var carouselItem = imageTemplate.clone()
603
      .addClass(index === 0 ? 'active' : '');
604
605
    if (item.thumb_url) {
606
      carouselItem.find('.carousel-image').css('background-image', 'url(\'' + item.url + '?timestamp=' + item.time + '\')');
607
    } else {
608
      carouselItem.find('.carousel-image').css('width', '50vh').append($('<div>').addClass('mime-icon ico-' + item.icon));
609
    }
610
611
    carouselItem.find('.carousel-label').attr('target', '_blank').attr('href', item.url)
612
      .append(item.name)
613
      .append($('<i class="fas fa-external-link-alt ml-2"></i>'));
614
615
    carousel.children('.carousel-inner').append(carouselItem);
616
617
    var carouselIndicator = indicatorTemplate.clone()
618
      .addClass(index === 0 ? 'active' : '')
619
      .attr('data-slide-to', index);
620
    carousel.children('.carousel-indicators').append(carouselIndicator);
621
  });
622
623
624
  // carousel swipe control
625
  var touchStartX = null;
626
627
  carousel.on('touchstart', function (event) {
628
    var e = event.originalEvent;
629
    if (e.touches.length == 1) {
0 ignored issues
show
Best Practice introduced by
Comparing e.touches.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
630
      var touch = e.touches[0];
631
      touchStartX = touch.pageX;
632
    }
633
  }).on('touchmove', function (event) {
634
    var e = event.originalEvent;
635
    if (touchStartX != null) {
0 ignored issues
show
Best Practice introduced by
Comparing touchStartX to null using the != operator is not safe. Consider using !== instead.
Loading history...
636
      var touchCurrentX = e.changedTouches[0].pageX;
637
      if ((touchCurrentX - touchStartX) > 60) {
638
        touchStartX = null;
639
        carousel.carousel('prev');
640
      } else if ((touchStartX - touchCurrentX) > 60) {
641
        touchStartX = null;
642
        carousel.carousel('next');
643
      }
644
    }
645
  }).on('touchend', function () {
646
    touchStartX = null;
647
  });
648
  // end carousel swipe control
649
650
  notify(carousel);
651
}
652
653
function move(items) {
654
  performLfmRequest('move', { items: items.map(function (item) { return item.name; }) })
655
    .done(refreshFoldersAndItems);
656
}
657
658
function getUrlParam(paramName) {
659
  var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
660
  var match = window.location.search.match(reParam);
661
  return ( match && match.length > 1 ) ? match[1] : null;
662
}
663
664
function use(items) {
665
  function useTinymce3(url) {
666
    if (!usingTinymce3()) { return; }
667
668
    var win = tinyMCEPopup.getWindowArg("window");
0 ignored issues
show
Bug introduced by
The variable tinyMCEPopup seems to be never declared. If this is a global, consider adding a /** global: tinyMCEPopup */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
669
    win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;
670
    if (typeof(win.ImageDialog) != "undefined") {
671
      // Update image dimensions
672
      if (win.ImageDialog.getImageData) {
673
        win.ImageDialog.getImageData();
674
      }
675
676
      // Preview if necessary
677
      if (win.ImageDialog.showPreviewImage) {
678
        win.ImageDialog.showPreviewImage(url);
679
      }
680
    }
681
    tinyMCEPopup.close();
682
  }
683
684
  function useTinymce4AndColorbox(url) {
685
    if (!usingTinymce4AndColorbox()) { return; }
686
687
    parent.document.getElementById(getUrlParam('field_name')).value = url;
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
688
689
    if(typeof parent.tinyMCE !== "undefined") {
690
      parent.tinyMCE.activeEditor.windowManager.close();
691
    }
692
    if(typeof parent.$.fn.colorbox !== "undefined") {
693
      parent.$.fn.colorbox.close();
694
    }
695
  }
696
697
  function useTinymce5(url){
698
    if (!usingTinymce5()) { return; }
699
700
    parent.postMessage({
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
701
      mceAction: 'insert',
702
      content: url
703
    });
704
705
    parent.postMessage({ mceAction: 'close' });
706
  }
707
708
  function useCkeditor3(url) {
709
    if (!usingCkeditor3()) { return; }
710
711
    if (window.opener) {
712
      // Popup
713
      window.opener.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
714
    } else {
715
      // Modal (in iframe)
716
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
717
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorCleanUpFuncNum'));
718
    }
719
  }
720
721
  function useFckeditor2(url) {
722
    if (!usingFckeditor2()) { return; }
723
724
    var p = url;
725
    var w = data['Properties']['Width'];
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
726
    var h = data['Properties']['Height'];
727
    window.opener.SetUrl(p,w,h);
728
  }
729
730
  var url = items[0].url;
731
  var callback = getUrlParam('callback');
732
  var useFileSucceeded = true;
733
734
  if (usingWysiwygEditor()) {
735
    useTinymce3(url);
736
737
    useTinymce4AndColorbox(url);
738
739
    useTinymce5(url);
740
741
    useCkeditor3(url);
742
743
    useFckeditor2(url);
744
  } else if (callback && window[callback]) {
745
    window[callback](getSelectedItems());
746
  } else if (callback && parent[callback]) {
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
747
    parent[callback](getSelecteditems());
748
  } else if (window.opener) { // standalone button or other situations
749
    window.opener.SetUrl(getSelectedItems());
750
  } else {
751
    useFileSucceeded = false;
752
  }
753
754
  if (useFileSucceeded) {
755
    if (window.opener) {
756
      window.close();
757
    }
758
  } else {
759
    console.log('window.opener not found');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
760
    // No editor found, open/download file using browser's default method
761
    window.open(url);
762
  }
763
}
764
//end useFile
765
766
// ==================================
767
// ==     WYSIWYG Editors Check    ==
768
// ==================================
769
770
function usingTinymce3() {
771
  return !!window.tinyMCEPopup;
772
}
773
774
function usingTinymce4AndColorbox() {
775
  return !!getUrlParam('field_name');
776
}
777
778
function usingTinymce5(){
779
    return !!getUrlParam('editor');
780
}
781
782
function usingCkeditor3() {
783
  return !!getUrlParam('CKEditor') || !!getUrlParam('CKEditorCleanUpFuncNum');
784
}
785
786
function usingFckeditor2() {
787
  return window.opener && typeof data != 'undefined' && data['Properties']['Width'] != '';
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
788
}
789
790
function usingWysiwygEditor() {
791
  return usingTinymce3() || usingTinymce4AndColorbox() || usingTinymce5() || usingCkeditor3() || usingFckeditor2();
792
}
793
794
// ==================================
795
// ==            Others            ==
796
// ==================================
797
798
function defaultParameters() {
799
  return {
800
    working_dir: $('#working_dir').val(),
801
    type: $('#type').val(),
802
    keyword: $('#keyword').val(),
803
  };
804
}
805
806
function notImp() {
807
  notify('Not yet implemented!');
808
}
809
810
function notify(body, callback) {
811
  $('#notify').find('.btn-primary').toggle(callback !== undefined);
812
  $('#notify').find('.btn-primary').unbind().click(callback);
813
  $('#notify').modal('show').find('.modal-body').html(body);
814
}
815
816
function dialog(title, value, callback) {
817
  $('#dialog').find('input').val(value);
818
  $('#dialog').on('shown.bs.modal', function () {
819
    $('#dialog').find('input').focus();
820
  });
821
  $('#dialog').find('.btn-primary').unbind().click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
822
    callback($('#dialog').find('input').val());
823
  });
824
  $('#dialog').modal('show').find('.modal-title').text(title);
825
}
826